/*************************************
 * Created by WebStorm
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time :2024/2/6 13:33
 Desc :
 **************************************/

import {computed, ComputedRef, onMounted, ref, unref, watch, watchEffect} from 'vue';
import {BasicTableProps} from '../types/Table.ts'
import {http} from '@/util/http';
import {paginationSetting} from '@/config';
import {PaginationProps} from '../types/Pagination.ts';
import {isBoolean} from '@/util/is.ts';

export function useDataSource(props: ComputedRef<BasicTableProps>, {
    getPaginationInfo,
    setPagination,
    setLoading,
    tableData
}, emit) {
    const dataSourceRef = ref<any>([]);
    watchEffect(() => {
        tableData.value = unref(dataSourceRef);
    });
    watch(() => unref(props).data,
        () => {
            const {data}: any = unref(props);
            data && (dataSourceRef.value = data);
        },
        {
            immediate: true,
        }
    );
    const getDataSourceRef = computed(() => {
        const dataSource = unref(dataSourceRef);
        if (!dataSource || dataSource.length === 0) {
            return dataSource;
        }
        return dataSource;
    });
    //请求数据
    const fetch = async (opt?: any) => {
        try {
            setLoading(true);
            const {methods, pagination, params, request, listUrl}: any = unref(props);
            //组装分页信息
            const pageField = paginationSetting.pageField;
            const sizeField = paginationSetting.sizeField;
            const totalField = paginationSetting.totalField;
            const listField = paginationSetting.listField;
            const itemCount = paginationSetting.itemCount;
            const {page, pageSize} = unref(getPaginationInfo) as PaginationProps;
            let pageParams = {};
            if ((isBoolean(pagination) && !pagination) || isBoolean(getPaginationInfo)) {
                pageParams = {};
            } else {
                pageParams[pageField] = (opt && opt[pageField]) || page;
                pageParams[sizeField] = pageSize;
            }
            const paramsObj = {
                ...pageParams,
                ...params
            };
            if (!listUrl && request == null) { //同步数据
                const {data}: any = unref(props);
                dataSourceRef.value = data;
            } else { //异步数据
                let res_data: any;
                if (request || listUrl) {
                    if (!request) {
                        res_data = await request_list(paramsObj, methods);
                    } else {
                        res_data = await request(params)
                    }
                }
                const {data} = res_data;
                let resultInfo: any;
                let totalPage: number = 0;
                if (pageParams && pageParams[pageField]) {
                    //有分页时
                    totalPage = data[totalField];
                    const currentPage = data[pageField];
                    resultInfo = data[listField] ? data[listField] : [];
                    setPagination({
                        [pageField]: currentPage,
                        [totalField]: totalPage,
                        [itemCount]: data.total || 0,
                    });
                    if (resultInfo.length === 0) {
                        opt[pageField] = currentPage > 1 ? currentPage - 1 : 1;
                        await fetch(opt);
                    }
                    if (opt && opt[pageField]) {
                        setPagination({
                            [pageField]: opt[pageField] || 1,
                            [itemCount]: data.total || 0,
                        });
                    }
                } else {
                    //没有分页时
                    if (data.hasOwnProperty(listField)) {
                        resultInfo = data[listField];
                    } else {
                        resultInfo = data;
                    }
                }
                dataSourceRef.value = resultInfo;
                emit("fetch-success", {
                    items: unref(resultInfo),
                    totalPage,
                });
            }
        } catch (e) {
            emit("fetch-error", e);
            dataSourceRef.value = [];
        } finally {
            setLoading(false);
        }
    }

    //刷新数据
    async function reload(opt?: any) {
        await fetch(opt);
    }

    async function request_list(params: any, methods: string) {
        const {listUrl}: any = unref(props);
        return await http.request({
                url: listUrl,
                method: methods,
                params,
            }
        );
    }

    onMounted(() => {
        setTimeout(() => {
            fetch().then(_r => {
            });
        }, 16)
    })
    return {
        fetch,
        reload,
        getDataSourceRef,
    }
}